<template>
  <div>
    <top-nav-bar :applyPageRoute="printtitle" @back="back"></top-nav-bar>
    <a-card :bordered="false">
      <a-spin :spinning="loading">
        <a-form-model ref="form" :rules="rules" v-bind="layout" :model="form">
          <a-form-model-item label="直播名称" prop="name">
            <a-input v-model="form.name" placeholder="请输入" style="width: 300px" />
          </a-form-model-item>
          <a-form-model-item label="直播模式">
            <a-radio-group name="radioGroup" v-model="form.type">
              <a-radio
                :value="1"
                style="
                  vertical-align: top;
                  background: #fafafa;
                  margin-right: 15px;
                  padding: 5px 10px;
                  border-radius: 8px;
                "
              >
                大班直播
                <a-card
                  :bordered="false"
                  style="background: #fafafa"
                  :bodyStyle="{ width: '300px', padding: 0, 'padding-top': '5px' }"
                >
                  <span style="white-space: normal; height: 40px; display: inline-block"
                    >支持学员文字互动、回答：最多1000名学员</span
                  >
                </a-card>
              </a-radio>
              <a-radio
                :value="2"
                style="
                  vertical-align: top;
                  background: #fafafa;
                  margin-right: 15px;
                  padding: 5px 10px;
                  border-radius: 8px;
                "
              >
                大班互动
                <a-card
                  :bordered="false"
                  style="background: #fafafa"
                  :bodyStyle="{ width: '300px', padding: 0, 'padding-top': '5px' }"
                >
                  <span style="white-space: normal"
                    >支持学员文字互动、回答、视频互动：最多1000名学员，最多支持与12名学员视频互动</span
                  >
                </a-card>
              </a-radio>
              <a-radio
                :value="3"
                style="
                  vertical-align: top;
                  background: #fafafa;
                  margin-right: 15px;
                  padding: 5px 10px;
                  border-radius: 8px;
                "
              >
                小班互动
                <a-card
                  :bordered="false"
                  style="background: #fafafa"
                  :bodyStyle="{ width: '300px', padding: 0, 'padding-top': '5px' }"
                >
                  <span style="white-space: normal"
                    >支持学员文字互动、回答、视频互动：最多12名学员，最多支持与所有学员视频互动</span
                  >
                </a-card>
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="上课时间" prop="end_time">
            <a-date-picker v-model="form.class_date" :disabled-date="disabledDate" placeholder="请选择上课日期" />
            <a-time-picker
              :disabled="!form.class_date"
              style="margin-left: 10px"
              format="HH:mm"
              v-model="form.start_time"
            />~
            <a-time-picker
              v-model="form.end_time"
              :disabled-hours="disabledHours"
              :disabled-minutes="disabledMinutes"
              :disabled="!form.start_time"
              format="HH:mm"
            />
            <div style="color:#ccc:">
              老师可以在
              <span style="margin: 0 5px">直播时</span>主动结束直播
            </div>
          </a-form-model-item>
          <a-form-model-item>
            <template slot="label">
              <span>
                <span
                  style="
                    display: inline-block;
                    margin-right: 4px;
                    color: #f5222d;
                    font-size: 14px;
                    font-family: SimSun, sans-serif;
                    line-height: 1;
                  "
                  >*</span
                >
                封面图</span
              >
            </template>
            <uploadImg ref="uploadImg" @imgUrl1="coverUrl" :defaultImg="coverIMG" @loading="changeLoading" @remove="removeCoverImg" />
            <div style="color:#ccc:">用于直播列表和详情展示，图片推荐尺寸：800X450</div>
          </a-form-model-item>
          <a-form-model-item label="上课老师" prop="teacher_id">
            <a-select v-model="form.teacher_id" placeholder="请选择" allowClear style="width: 300px">
              <a-select-option v-for="(item, index) in teacherList" :key="index" :value="item.id">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="上课学员">
            <div>
              添加、移除学员请保存后返回，点击操作栏中的学员名单进行操作
              <!-- 已选择{{form.student_count}}名学员 -->
              <!-- <p>添加、移除学员请保存后返回，点击操作栏中的学员名单进行操作</p> -->
            </div>
          </a-form-model-item>
          <a-form-model-item label="直播简介">
            <a-textarea
              v-model="form.intro"
              placeholder="简单介绍下这次课吧(最多输入250个字)"
              :maxLength="250"
              style="width: 500px"
              :rows="4"
            />
          </a-form-model-item>
          <a-form-model-item :wrapperCol="{ span: 3, offset: 2 }">
            <a-button type="primary" @click="submit('form')">保存</a-button>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
      <student-model ref="studentM" @reload="studentModelReturnData" :studentArr="form.student_ids"></student-model>
    </a-card>
  </div>
</template>

<script>
import topNavBar from '@/components/topNavBar/topNavBar'
import { teacherList } from '@/api/teacher'
import studentModel from '@/components/student'
import { editLives, infoLives } from '@/api/lives'
import uploadImg from '@/components/uploadImg'
import moment from 'moment'
export default {
  components: {
    topNavBar,
    studentModel,
    uploadImg,
  },
  name: 'createLives',
  data() {
    return {
      printtitle: '编辑直播课',
      layout: {
        labelCol: { span: 2 },
        wrapperCol: { span: 20 },
      },
      loading: false,
      id: null,
      coverIMG: '',
      form: {
        name,
        type: 1,
        class_date: undefined,
        start_time: undefined,
        end_time: undefined,
        student_count: 0,
        teacher_id: undefined,
      },
      rules: {
        name: [{ required: true, message: '请输入直播课名称！' }],
        teacher_id: [{ required: true, message: '请选择上课老师！' }],
        end_time: [{ required: true, message: '请选择上课时间！' }],
      },
      teacherList: [],
      studentInfo: [],
    }
  },
  created() {
    teacherList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        this.teacherList = res.data
      })
      .finally(() => {
        this.reload(Number(this.$route.query.id))
      })
  },
  methods: {
    disabledDate(current) {
      return current && current < moment(new Date()).add(-1, 'days')
    },
    reload(id) {
      this.loading = true
      this.id = id
      infoLives(id)
        .then((res) => {
          this.$nextTick(() => {
            let params = JSON.parse(JSON.stringify(res))
            params.class_date = moment(params.class_date)
            params.start_time = moment(moment().format('YYYY-MM-DD') + '  ' + params.start_time + ':00')
            params.end_time = moment(moment().format('YYYY-MM-DD') + '  ' + params.end_time + ':00')
            params.teacher_id = params.teacher ? Number(params.teacher.id) : undefined
            this.$nextTick(()=>{
              this.coverIMG = params.cover_image
              this.$refs.uploadImg.setDefault(params.cover_image)
            })
            this.form = params
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          params.class_date = moment(params.class_date).format('YYYY-MM-DD')
          params.start_time = moment(new Date(params.start_time).valueOf()).format('HH:mm')
          params.end_time = moment(new Date(params.end_time).valueOf()).format('HH:mm')
          if (!params.cover_image) {
            this.$message.error('请上传封面图')
            return
          }
          this.loading = true
          editLives(Object.assign(params, { school_id: this.$store.state.user.school }), this.id)
            .then((res) => {
              this.$message.success('保存成功')
              this.back()
            })
            .catch((err) => {
              if (err.data.message) {
                this.$message.error(err.data.message || '保存失败')
              } else {
                this.$message.error('保存失败')
              }
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    studentModelReturnData(e) {
      //学生组件返回数据
      let arr = []
      e.forEach((val) => {
        arr.push(val.id)
      })
      this.form.student_ids = arr
      this.studentInfo = e
    },
    showStudent() {
      this.$refs.studentM.showModel()
    },
    moment,
    coverUrl(e) {
      this.form.cover_image = e
    },
    changeLoading(e) {
      this.loading = e
    },
    changeClassDate(date, dateS) {
      this.form.class_date = dateS
    },
    disabledHours() {
      let hour = Number(moment(this.form.start_time).format('HH'))
      let data = []
      for (let i = 0; i < hour; i++) {
        data.push(i)
      }
      return data
    },
    disabledMinutes() {
      let hour = Number(moment(this.form.start_time).format('HH'))
      let endHour = Number(moment(this.form.end_time).format('HH'))
      let minutes = Number(moment(this.form.start_time).format('mm'))
      let data = []
      if (endHour > hour) {
      } else {
        for (let i = 0; i < minutes; i++) {
          data.push(i)
        }
      }
      return data
    },
    changeStartTime(date, dateString) {
      this.form.start_time = dateString
      this.$forceUpdate()
    },
    changeEndTime(date, dateString) {
      if (moment(this.form.start_time).valueOf() > moment(date).valueOf()) {
        this.$message.warning('结束时间不能大于开始时间')
        this.form.end_time = undefined
        this.$forceUpdate()
        return
      } else {
        this.form.end_time = dateString
      }
      this.$forceUpdate()
    },
    back() {
      this.$router.go(-1)
    },
    removeCoverImg() {
      this.form.cover_image = ''
    },
    rTime(date) {
      let json_date = new Date(date).toJSON()
      return new Date(new Date(json_date) + 8 * 3600 * 1000)
        .toISOString()
        .replace(/T/g, ' ')
        .replace(/\.[\d]{3}Z/, '')
    },
  },
}
</script>

<style lang="scss" scoped>
.primaryCOLOR {
  color: #1890ff;
}
.longestText {
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
  .overFlowHidden {
    display: inline-block;
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
    position: relative;
    top: -1px;
  }
}
</style>